<?php declare(strict_types=1);

namespace app\admin\service;

use app\common\model\Tag;
use think\Exception;
use think\facade\Log;

class TagService
{
    /**
     * 列表
     * @return void
     */
    public function getTagList($type, $pageSize)
    {
        $model = new Tag();
        return $model->where('type', $type)->order('id desc')->paginate($pageSize);
    }

    /**
     * 获取所有Tag
     * @param $type
     * @return Tag[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAllTags($type = 0){
        $model = new Tag();
        return $model
            ->where(function ($query) use ($type) {
                if($type){
                    $query->where('type', $type);
                }
            })
            ->field('id,type,name')->select();
    }

    /**
     * 更新数据
     * @param $data
     * @return void
     */
    public function updateOrInsert($data)
    {
        if (empty($data)) {
            return false;
        }
        $model = new Tag();
        try {
            if (isset($data['id'])) {
                $item = $model->find($data['id']);
                $item->save($data);
            } else {
                $model->save($data);
            }
            return true;
        } catch (\Exception $e) {
            Log::error("updateOrInsert tag error:" .$e->getMessage());
            return false;
        }
    }

    /**
     * 删除记录
     * @param $id
     * @return void
     */
    public function delete($id)
    {
        $model = new Tag();
        return $model->where('id', $id)->update(['status'=>0]);
    }

    /**
     * 查询一条记录
     * @param $id
     * @return void
     */
    public function getOne($id)
    {
        $model = new Tag();
        return $model->find($id);
    }

    /**
     * 获取标签名称
     * @param $ids
     * @return void
     */
    public function getTagName($ids){
        $name = '';
        $model = new Tag();
        if (is_array($ids)) {
            $idsArr = $model->whereIn('id', $ids)->column('name');
            if (!empty($idsArr)) {
                $name = implode(',', $idsArr);
            }
        } else {
            $ids = explode(',', $ids);
            $idsArr = $model->whereIn('id', $ids)->column('name');
            if (!empty($idsArr)) {
                $name = implode(',', $idsArr);
            }
        }
        return $name;
    }
}